﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace orderCreater
{
    public partial class Frm531Bl : Form
    {
        public MySqlHelp db = new MySqlHelp(ConfigurationManager.AppSettings["ConnectionString-531"]);
        public tool _tools = new tool();

        public Frm531Bl()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.sr_bgw.WorkerSupportsCancellation = true;
            this.jf_bgw.WorkerSupportsCancellation = true;
            this.sr_btn_stop.Enabled = false;

            this.sr_tb_goodIds.Text = ConfigurationManager.AppSettings["goodsIds-531Order"];


        }

        public string CreateUser() 
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds = db.ExecuteSqlDataSet("SELECT * FROM db_v_buyer  AS t1  JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `db_v_buyer`)-(SELECT MIN(id) FROM db_v_buyer))+(SELECT MIN(id) FROM db_v_buyer)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;");
            dt = ds.Tables[0];
            DataRow dr = dt.Rows[0];
            Random rd = new Random();

            int rtnid = 0;

            string buyerid = dr["id"].ToString();
            string userid = dr["userid"].ToString();
            string name = dr["name"].ToString();
            string cn_name = name;
            name = name.Replace("先生", "").Replace("小姐","").Replace("女士","");
            string mobile = dr["mobile"].ToString();
            string username = _tools.GetPinyin(name);
            string email = _tools.getRandEmail(username);
            int _rd = rd.Next(0,2);
            if (_rd == 1) 
            {
                username = mobile;
            }
            string time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            if (userid.Length > 0)
            {
                rtnid = int.Parse(userid);
            }
            else 
            {
                if (db.Exists("select * from db_member where member_name='"+username+"';")) 
                {
                    CreateUser();
                }

                string sql = "INSERT INTO `db_member` ( `member_name`, `member_truename`, `member_avatar`, `member_sex`, `member_birthday`, `member_passwd`, `member_paypwd`, `member_email`, `member_email_bind`, `member_mobile`, `member_mobile_bind`, `member_qq`, `member_ww`, `member_login_num`, `member_time`, `member_login_time`, `member_old_login_time`, `member_login_ip`, `member_old_login_ip`, `member_qqopenid`, `member_qqinfo`, `member_sinaopenid`, `member_sinainfo`, `member_points`, `available_predeposit`, `freeze_predeposit`, `available_rc_balance`, `freeze_rc_balance`, `inform_allow`, `is_buy`, `is_allowtalk`, `member_state`, `member_snsvisitnum`, `member_areaid`, `member_cityid`, `member_provinceid`, `member_areainfo`, `member_privacy`, `member_quicklink`, `member_exppoints`, `inviter_id`) VALUES ('" + username + "', '" + cn_name + "', '', 0, NULL, 'b3b8f6c7ebee1e938c8b29ebe66c8906', '', '" + email + "', 1, '" + mobile + "', 1, '', '', 1, '" + time + "', '" + time + "', '" + time + "', '127.0.0.1', '127.0.0.1', '', '', '', '', 0, 0.00, 0.00, 0.00, 0.00, 1, 1, 1, 1, 0, NULL, NULL, NULL, NULL, '', '', 0, NULL);SELECT LAST_INSERT_ID();";

                rtnid = int.Parse(db.Query(sql).Tables[0].Rows[0][0].ToString());
            }

            db.ExecuteSql("update db_v_buyer set userId=" + rtnid.ToString() + ",useCount=useCount+1 where id=" + buyerid + ";");

            return rtnid.ToString();
        }
        
        public DataRow getRandGoodsByIds(string ids,string cityName) 
        {
            string sql = "SELECT * FROM db_goods WHERE goods_id IN(" + ids + ") and goods_state=1 and gc_id=1074 ORDER BY RAND() LIMIT 1;";

            DataSet ds = new DataSet();

            ds = db.ExecuteSqlDataSet(sql);

            return ds.Tables[0].Rows[0];

        }



        public DataRow getRandAccepter()
        {

            DataSet ds = new DataSet();

            ds = db.ExecuteSqlDataSet("SELECT * FROM db_v_accepter  AS t1  JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `db_v_accepter`)-(SELECT MIN(id) FROM db_v_accepter))+(SELECT MIN(id) FROM db_v_accepter)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;");

            if (ds.Tables[0].Rows.Count < 1)
            {
                ds = db.ExecuteSqlDataSet("SELECT * FROM db_v_accepter where city_id not in(36,39,40,62,176,203,289,291,385,415) ORDER BY rand();");
            }

            db.ExecuteSql("update db_v_accepter set useCount=useCount+1 where id=" + ds.Tables[0].Rows[0]["id"].ToString() + ";");

            return ds.Tables[0].Rows[0];

        }

        public DataRow getRandAccepter_zc()
        {

            DataSet ds = new DataSet();

            ds = db.ExecuteSqlDataSet("SELECT * FROM db_v_accepter  AS t1  JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `db_v_accepter`)-(SELECT MIN(id) FROM db_v_accepter))+(SELECT MIN(id) FROM db_v_accepter)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;");

            if (ds.Tables[0].Rows.Count < 1)
            {
                ds = db.ExecuteSqlDataSet("SELECT * FROM db_v_accepter where city_id in(36,39,40,62,176,203,289,291,385,415) ORDER BY rand();");
            }

            db.ExecuteSql("update db_v_accepter set useCount=useCount+1 where id=" + ds.Tables[0].Rows[0]["id"].ToString() + ";");

            return ds.Tables[0].Rows[0];

        }

        public string getRandBuyer() 
        {
            string userId = "";
            userId = this.CreateUser();
            return userId;
        }

        public DataRow getRandShop() 
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds = db.ExecuteSqlDataSet("SELECT * FROM db_shops where Commentcount=0 and `status`=2 ORDER BY RAND() ASC LIMIT 1;");
            dt = ds.Tables[0];
            return dt.Rows[0];
        }

        private string CreateSendTime(string OrderTime)
        {
            string returnString = string.Empty;
            string dateStr = DateTime.Parse(OrderTime).ToShortDateString();
            string timeStr = DateTime.Parse(OrderTime).Hour.ToString();
            Random rd = new Random();
            if (DateTime.Parse(OrderTime).Hour > 18)
            {
                timeStr = rd.Next(9, 21).ToString();
                dateStr = DateTime.Parse(OrderTime).AddDays(1).ToShortDateString();
            }
            else
            {
                timeStr = rd.Next(int.Parse(timeStr) + 2, 21).ToString();
            }
            
            returnString = dateStr + " " + timeStr + ":00:00";
            return returnString;
        }

        private string CreatePayTime(string OrderTime) 
        {
            string returnString = string.Empty;
            Random rd = new Random();
            int addM = rd.Next(1, 11);
            DateTime newDate = DateTime.Parse(OrderTime).AddMinutes(addM);

            returnString = newDate.ToString("yyyy-MM-dd HH:mm:ss");
                                 // returnString = newDate.ToShortDateString() + " " + newDate.Hour.ToString() + ":" + newDate.Minute.ToString() + ":" + newDate.Second.ToString();
            return returnString;
        }

        private string CreateDelayTime(string sendTime)
        {
            string returnString = string.Empty;
            Random rd = new Random();
            string dateStr = DateTime.Parse(sendTime).ToShortDateString();
            int timeStr = DateTime.Parse(sendTime).Hour - 2 + rd.Next(0, 2);

            string h = timeStr.ToString();
            string m = rd.Next(0, 31).ToString();
            string s = rd.Next(0, 60).ToString();

            if (h.Length < 2)
            {
                h = "0" + h;
            }
            if (m.Length < 2)
            {
                m = "0" + m;
            }
            if (s.Length < 2)
            {
                s = "0" + s;
            }
            returnString = dateStr + " " + h + ":" + m + ":" + s;
            return returnString;
        }

        private string CreateFinnshedTime(string sendTime) 
        {
            string returnString = string.Empty;
            Random rd = new Random();
            int addD = rd.Next(0,4);
            int addH = rd.Next(1,24);
            int addM = rd.Next(0,60);
            int addS = rd.Next(0,60);
            DateTime newDate = DateTime.Parse(sendTime).AddDays(addD).AddHours(addH).AddMinutes(addM).AddSeconds(addS);

            returnString = newDate.ToShortDateString() + " " + newDate.Hour.ToString() + ":" + newDate.Minute.ToString() + ":" + newDate.Second.ToString();

            return returnString;
        }


        static Byte[] StringToByte(String s, Encoding encoding)
        {
            return encoding.GetBytes(s);
        }

        static String ByteToString(Byte[] b, Encoding encoding)
        {
            return encoding.GetString(b);
        }

        private void sr_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            this.sr_btn_start.Enabled = false;
            this.sr_btn_stop.Enabled = true;
            this.sr_tb_priceArea.Enabled = false;
            this.sr_tb_goodIds.Enabled = false;
            this.sr_dt_time.Enabled = false;
            this.tb_sr_payPrice.Enabled = false;
            this.sr_tb_logs.Text = "";

            decimal total = 0;
            int count = 0;
            StringBuilder _logs = new StringBuilder();

            do
            {
                if (worker.CancellationPending || total > decimal.Parse(this.sr_tb_priceArea.Text.ToString()))
                {

                    e.Cancel = true;

                    break;
                }
                else
                {
                    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                    string userId = this.getRandBuyer();

                    DataRow accepter = this.getRandAccepter();

                    string accepterName = accepter["name"].ToString();

                    string accepterMobile = accepter["mobile"].ToString();

                    string accepterAddress = accepter["address"].ToString();

                    string accepterAddressLength = StringToByte(accepterAddress, Encoding.UTF8).Length.ToString();

                    string accepterProvince = accepter["province"].ToString();

                    string accepterCity = accepter["city"].ToString();

                    string province_id = accepter["province_id"].ToString();

                    string city_id = accepter["city_id"].ToString();

                    string area_id = accepter["area_id"].ToString();

                    DataRow buyer = db.ExecuteSqlDataSet("SELECT * FROM db_member where member_id=" + userId + "  LIMIT 1;").Tables[0].Rows[0];

                    DataRow goods = this.getRandGoodsByIds(this.sr_tb_goodIds.Text.ToString(),accepterCity);

                    DataRow shop = this.getRandShop();

                    string orderCode = _tools.CreateOrderCode();

                    string payCode = _tools.createPayCode(buyer["member_id"].ToString());

                    string orderTimeStr = _tools.CreateOrderTime(this.sr_dt_time.Value.ToString("yyyy-MM-dd"));

                    string orderTime = ((DateTime.Parse(orderTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                    //string orderTimeStr = this.sr_dt_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    //string orderTime = ((this.sr_dt_time.Value.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                    string requestTime = ((DateTime.Parse(CreateSendTime(orderTimeStr)).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();



                    string isPay = _tools.IsPay();

                    if (isPay == "1" && city_id != "0" && !this.cb_sr_notPay.Checked)
                    {
                        string payTimeStr = CreatePayTime(orderTimeStr);

                        string payTime = ((DateTime.Parse(payTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                        string delayTime = ((DateTime.Parse(CreateDelayTime(CreateSendTime(orderTimeStr))).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                        string finnshedTime = ((DateTime.Parse(CreateFinnshedTime(CreateSendTime(orderTimeStr))).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                        string payType = "alipay";

                        string sql_order = "INSERT INTO `db_order` (`order_sn`, `pay_sn`, `store_id`, `store_name`, `buyer_id`, `buyer_name`, `buyer_email`, `add_time`, `payment_code`, `payment_time`, `finnshed_time`, `goods_amount`, `order_amount`, `rcb_amount`, `pd_amount`, `shipping_fee`, `evaluation_state`, `order_state`, `refund_state`, `lock_state`, `delete_state`, `refund_amount`, `delay_time`, `order_from`, `shipping_code`, `request_delivery_time`) VALUES ('" + orderCode + "', '" + payCode + "', '" + shop["ID"].ToString() + "', '" + shop["Name"].ToString() + "', '" + buyer["member_id"].ToString() + "', '" + buyer["member_name"].ToString() + "', '" + buyer["member_email"].ToString() + "', '" + orderTime + "', '"+payType+"', '"+payTime+"', '"+finnshedTime+"', '" + goods["goods_price"].ToString() + "', '" + goods["goods_price"].ToString() + "', '0.00', '0.00', '0.00', '0', '40', '0', '0', '0', '0.00', '"+delayTime+"', '1', '', '" + requestTime + "');SELECT LAST_INSERT_ID();";

                        string order_id = db.Query(sql_order).Tables[0].Rows[0][0].ToString();
                        ///////////////////////////////////////////////
                        if (this.sync_alipay_cb.Checked == true)
                        {
                            syncAlipay(orderCode, goods["goods_price"].ToString(), buyer["member_email"].ToString(), buyer["member_name"].ToString(), payTimeStr);
                        }
                        ///////////////////////////////////////////////
                        _logs.Insert(0, accepterName+" "+accepterMobile+" "+accepterProvince+" "+accepterCity+" "+accepterAddress+ "\r\n");

                        this.sr_tb_logs.Text = _logs.ToString();
                        ///////////////////////////////////////////////

                        string sql_order_common = "INSERT INTO `db_order_common` (`order_id`, `store_id`, `shipping_time`, `shipping_express_id`, `evaluation_time`, `evalseller_state`, `evalseller_time`, `order_message`, `order_pointscount`, `voucher_price`, `voucher_code`, `deliver_explain`, `daddress_id`, `reciver_name`, `reciver_info`, `reciver_province_id`, `reciver_city_id`, `reciver_area_id`, `invoice_info`, `promotion_info`, `dlyo_pickup_code`) VALUES ('" + order_id + "', '" + shop["ID"].ToString() + "', '0', '0', '0', '0', '0', '', '0', null, null, null, '0', '" + accepterName + "', 'a:6:{s:5:\"phone\";s:11:\"" + accepterMobile + "\";s:9:\"mob_phone\";s:11:\"" + accepterMobile + "\";s:9:\"tel_phone\";s:0:\"\";s:7:\"address\";s:" + accepterAddressLength + ":\"" + accepterAddress + "\";s:4:\"area\";s:0:\"\";s:6:\"street\";s:0:\"\";}', '" + province_id + "', '" + city_id + "', '" + area_id + "', 'a:0:{}', '', null);";

                        db.ExecuteSql(sql_order_common);

                        string sql_order_goods = "INSERT INTO `db_order_goods` (`order_id`, `goods_id`, `goods_name`, `goods_price`, `goods_num`, `goods_image`, `goods_pay_price`, `store_id`, `buyer_id`, `goods_type`, `promotions_id`, `commis_rate`, `gc_id`) VALUES ('" + order_id + "', '" + goods["goods_id"].ToString() + "', '" + goods["goods_name"].ToString() + "', '" + goods["goods_price"].ToString() + "', '1', '" + goods["goods_image"].ToString() + "', '" + goods["goods_price"].ToString() + "', '" + shop["ID"].ToString() + "', '" + buyer["member_id"].ToString() + "', '1', '0', '0', '" + goods["gc_id"].ToString() + "');";

                        db.ExecuteSql(sql_order_goods);

                        string sql_order_pay = "INSERT INTO `db_order_pay` (`pay_sn`, `buyer_id`, `api_pay_state`) VALUES ('" + payCode + "', '" + buyer["member_id"].ToString() + "', '1');";

                        db.ExecuteSql(sql_order_pay);

                        string sql_log_pay = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES ("+order_id+", '收到了货款', '"+payTime+"', '商家', 'dl_sk_"+city_id+"', '20');";

                        db.ExecuteSql(sql_log_pay);

                        string sql_log_delay = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES (" + order_id + ", '发出了货物 ( 编辑了发货信息 )', '" + delayTime + "', '商家', 'dl_ps_" + city_id + "', '30');";

                        db.ExecuteSql(sql_log_delay);

                        string sql_log_finnshed = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES (" + order_id + ", '签收了货物', '" + finnshedTime + "', '买家', '" + buyer["member_name"].ToString() + "', '40');";

                        db.ExecuteSql(sql_log_finnshed);

                        db.ExecuteSql("update db_order_common set shipping_time='"+delayTime+"' where order_id=" + order_id + ";");

                        db.ExecuteSql("INSERT INTO `db_v_order` (`orderId`, `orderCode`, `shopId`) VALUES (" + order_id + ", '" + orderCode + "', " + shop["ID"].ToString() + ");");
                    }
                    else 
                    {
                        string sql_order = "INSERT INTO `db_order` (`order_sn`, `pay_sn`, `store_id`, `store_name`, `buyer_id`, `buyer_name`, `buyer_email`, `add_time`, `payment_code`, `payment_time`, `finnshed_time`, `goods_amount`, `order_amount`, `rcb_amount`, `pd_amount`, `shipping_fee`, `evaluation_state`, `order_state`, `refund_state`, `lock_state`, `delete_state`, `refund_amount`, `delay_time`, `order_from`, `shipping_code`, `request_delivery_time`) VALUES ('" + orderCode + "', '" + payCode + "', '" + shop["ID"].ToString() + "', '" + shop["Name"].ToString() + "', '" + buyer["member_id"].ToString() + "', '" + buyer["member_name"].ToString() + "', '" + buyer["member_email"].ToString() + "', '" + orderTime + "', 'online', '0', '0', '" + goods["goods_price"].ToString() + "', '" + goods["goods_price"].ToString() + "', '0.00', '0.00', '0.00', '0', '10', '0', '0', '0', '0.00', '0', '1', '', '" + requestTime + "');SELECT LAST_INSERT_ID();";

                        string order_id = db.Query(sql_order).Tables[0].Rows[0][0].ToString();

                        ///////////////////////////////////////////////
                        _logs.Insert(0, accepterName + " " + accepterMobile + " " + accepterProvince + " " + accepterCity + " " + accepterAddress + "\r\n");

                        this.sr_tb_logs.Text = _logs.ToString();
                        ///////////////////////////////////////////////

                        string sql_order_common = "INSERT INTO `db_order_common` (`order_id`, `store_id`, `shipping_time`, `shipping_express_id`, `evaluation_time`, `evalseller_state`, `evalseller_time`, `order_message`, `order_pointscount`, `voucher_price`, `voucher_code`, `deliver_explain`, `daddress_id`, `reciver_name`, `reciver_info`, `reciver_province_id`, `reciver_city_id`, `reciver_area_id`, `invoice_info`, `promotion_info`, `dlyo_pickup_code`) VALUES ('" + order_id + "', '" + shop["ID"].ToString() + "', '0', '0', '0', '0', '0', '', '0', null, null, null, '0', '" + accepterName + "', 'a:6:{s:5:\"phone\";s:11:\"" + accepterMobile + "\";s:9:\"mob_phone\";s:11:\"" + accepterMobile + "\";s:9:\"tel_phone\";s:0:\"\";s:7:\"address\";s:" + accepterAddressLength + ":\"" + accepterAddress + "\";s:4:\"area\";s:0:\"\";s:6:\"street\";s:0:\"\";}', '" + province_id + "', '" + city_id + "', '" + area_id + "', 'a:0:{}', '', null);";

                        db.ExecuteSql(sql_order_common);

                        string sql_order_goods = "INSERT INTO `db_order_goods` (`order_id`, `goods_id`, `goods_name`, `goods_price`, `goods_num`, `goods_image`, `goods_pay_price`, `store_id`, `buyer_id`, `goods_type`, `promotions_id`, `commis_rate`, `gc_id`) VALUES ('" + order_id + "', '" + goods["goods_id"].ToString() + "', '" + goods["goods_name"].ToString() + "', '" + goods["goods_price"].ToString() + "', '1', '" + goods["goods_image"].ToString() + "', '" + goods["goods_price"].ToString() + "', '" + shop["ID"].ToString() + "', '" + buyer["member_id"].ToString() + "', '1', '0', '0', '" + goods["gc_id"].ToString() + "');";

                        db.ExecuteSql(sql_order_goods);

                        string sql_order_pay = "INSERT INTO `db_order_pay` (`pay_sn`, `buyer_id`, `api_pay_state`) VALUES ('" + payCode + "', '" + buyer["member_id"].ToString() + "', '0');";

                        db.ExecuteSql(sql_order_pay);

                        db.ExecuteSql("INSERT INTO `db_v_order` (`orderId`, `orderCode`, `shopId`) VALUES (" + order_id + ", '" + orderCode + "', " + shop["ID"].ToString() + ");");
                    }

                    

                    string _totalStr = string.Empty;

                    string _totalStrPay = string.Empty;

                    string _s_time = ((DateTime.Parse(this.sr_dt_time.Value.ToShortDateString()).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                    string _e_time = ((DateTime.Parse(this.sr_dt_time.Value.AddDays(1).ToShortDateString()).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

                    _totalStr = db.Query("select sum(order_amount) from db_order where add_time>'" + _s_time + "' and add_time<'" + _e_time + "';").Tables[0].Rows[0][0].ToString();

                    _totalStrPay = db.Query("select sum(order_amount) from db_order where add_time>'" + _s_time + "' and add_time<'" + _e_time + "' and order_state in (20,30,40);").Tables[0].Rows[0][0].ToString();

                    if (_totalStr.Length < 1 || _totalStr.Equals("NULL") || _totalStr.Equals("null"))
                    {
                        total = 0;
                    }
                    else
                    {
                        total = decimal.Parse(_totalStr);
                    }
                    count += 1;

                    _logs.Insert(0, "[" + DateTime.Now + "]成功录入一条订单信息到店铺：[" + shop["Name"].ToString() + "]。\r\n");

                    this.sr_lb_status.Text = "运行中……";

                    this.sr_tb_logs.Text = _logs.ToString();

                    this.sr_lb_count.Text = count.ToString();

                    this.sr_lb_totalPrice.Text = total.ToString();

                    this.lb_sr_pay.Text = _totalStrPay;

                    if (decimal.Parse(_totalStrPay) > decimal.Parse(this.tb_sr_payPrice.Text.Trim().ToString())) 
                    {
                        this.cb_sr_notPay.Checked = true;
                    }

                    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
            } while (!worker.CancellationPending);

            this.sr_lb_status.Text = "已停止！";

            this.sr_btn_start.Enabled = true;

            this.sr_btn_stop.Enabled = false;

            this.sr_tb_priceArea.Enabled = true;

            this.sr_tb_goodIds.Enabled = true;

            this.sr_dt_time.Enabled = true;

            this.tb_sr_payPrice.Enabled = true;
            
        }

        private void sr_bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.sr_lb_status.Text = "已停止！";
            }
        }

        private void sr_btn_start_Click(object sender, EventArgs e)
        {
            if (this.sr_tb_priceArea.Text.Length < 1) 
            {
                MessageBox.Show("请输入当日总金额。");
            }
            else if (this.tb_sr_payPrice.Text.Length < 1)
            {
                MessageBox.Show("请输入支付金额。");
            }
            else if (this.sr_tb_goodIds.Text.Length < 1)
            {
                MessageBox.Show("请输入产品ID。");
            }
            else 
            {
                this.sr_lb_status.Text = "系统初始化中……";

                this.sr_bgw.RunWorkerAsync();
            }
            
        }

        private void sr_btn_stop_Click(object sender, EventArgs e)
        {
            this.sr_lb_status.Text = "停止中……";

            sr_bgw.CancelAsync();
        }

        public static string syncAlipay(string _orderSn, string _orderPrice, string _account, string _fullName, string _tradeTime)
        {
            try
            {
                string url = "orderNo=" + _orderSn + "&";
                url = url + "tradeAmount=" + _orderPrice + "&";
                url = url + "otherAccountEmail=" + _account + "&";
                url = url + "otherAccountFullname=" + _fullName + "&";
                url = url + "sourceType=" + 1 + "&"; // 来源:1为531,2为我订花
                url = url + "tradeTime=" + _tradeTime;
                // string formUrl = "http://sync?.qqxhsd.com/api/trade/add";
                string formUrl = "https://alipay.22ca.com/index.php/Api/insertOrder3";
                string formData = url;                               //提交的参数

                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }

        private void jf_bgw_DoWork(object sender, DoWorkEventArgs e)
        {

        }
    }
}
